Ext.define('Bible.picker.Chapter', {
    extend: 'Ext.picker.Picker',
    xtype: 'biblechapterpicker',
    alternateClassName: 'Bible.ChapterPicker',

    /**
     * @event change
     * Fired when the value of this picker has changed and the done button is pressed.
     * @param {Ext.picker.Date} this This Picker
     * @param {Date} value The date value
     */

    config: {

        // TODO fullscreen is not working
        height: '100%',
        //fullscreen: true,
//        height: 330,


        bookText: 'Cartea',
        chapterText: 'Capitol'

        /**
         * @cfg {Object} value
         * Examples:
         * {book: 1, chapter: 4} = Genesa 4
         * @accessor
         */

        /**
         * @cfg {Array} slots
         * @hide
         * @accessor
         */
    },

    initialize: function() {
        this.callParent();

        this.on({
            scope: this,
            delegate: '> slot',
            slotpick: this.onSlotPick
        });
    },

    // TODO http://www.sencha.com/forum/showthread.php?189495-Datepicker-will-not-set-initial-value&p=760592
    setValue: function(value, animated) {
        //<debug>
        console.debug('setValue', value);
        //</debug>
        if(!this.getSlots()) {
            this.createSlots();
        }
        this.callParent([value, animated]);
    },

    getValue: function() {
        var values = {},
            chaptersInMonth, book, chapter,
            items = this.getItems().items,
            ln = items.length,
            item, i;
        //<debug>
        console.debug('ln: ', ln);
        //</debug>
        for (i = 0; i < ln; i++) {
            item = items[i];
            if (item instanceof Ext.picker.Slot) {
                //<debug>
                console.debug('getValue item.getName()', item.getName(), item.getValue());
                //</debug>

                values[item.getName()] = item.getValue();
            }
        }
        //<debug>
        console.debug('getValue values', values);
        //</debug>
        //if all the slots return null, we should not reutrn a date
        if (values.book === null && values.chapter === null) {
            return null;
        }

        book = Ext.isNumber(values.book) ? values.book : 1;
        chapter = Ext.isNumber(values.chapter) ? values.chapter : 1;

        if (chapter && book) {
            chaptersInMonth = this.getChaptersInBook(book);
        }
        chapter = (chaptersInMonth) ? Math.min(chapter, chaptersInMonth): chapter;
        //<debug>
        console.debug('book, chapter', book, chapter);
        //</debug>
        return {
            book: book,
            chapter: chapter
        };
    },

    // @private
    constructor: function() {
        this.callParent(arguments);
        this.createSlots();
    },

    /**
     * Generates all slots for all years specified by this component, and then sets them on the component
     * @private
     */
    createSlots: function() {
        var me        = this,
            slotOrder = ['book', 'chapter'],
            records   = booksRecords,
            slots     = [],
            books     = [],
            chapters  = [],
            ln, i,
            chaptersInBook;

        for (i = 0; i < records.length; i++) {
            books.push({
                text: records[i][1],
                value: i + 1
            });
        }

        chaptersInBook = me.getChaptersInBook(1);

        for (i = 0; i < chaptersInBook; i++) {
            chapters.push({
                text: i + 1,
                value: i + 1
            });
        }

        slotOrder.forEach(function(item) {
            slots.push(this.createSlot(item, books, chapters));
        }, me);

        me.setSlots(slots);
    },

    /**
     * Returns a slot config for a specified date.
     * @private
     */
    createSlot: function(name, books, chapters) {
        switch (name) {
            case 'book':
                return {
                    name: name,
                    align: 'left',
                    data: books,
                    title: this.getBookText(),
                    flex: 3
                };
            case 'chapter':
                return {
                    name: name,
                    align: 'right',
                    data: chapters,
                    title: this.getChapterText(),
                    flex: 1
                };
        }
    },

    onSlotPick: function() {
        var me = this,
            value = me.getValue(),
            slot = me.getChapterSlot(),
            book = value.book,
            chapter = value.chapter,
            chapters = [],
            chaptersInBook, i;

        if (!value || !slot) {
            return;
        }

        //get the new chapters of the book for this new book
        chaptersInBook = me.getChaptersInBook(book);

        // We dont need to update the slot chapters unless it has changed
        if (slot.getData().length == chaptersInBook - 1) {
            return;
        }

        for (i = 0; i < chaptersInBook; i++) {
            chapters.push({
                text: i + 1,
                value: i + 1
            });
        }

        // Now we have the correct amounnt of chapters for the chapter slot, lets update it
        var store = slot.getStore(),
            viewItems = slot.getViewItems(),
            valueField = slot.getValueField(),
            index, item;

        slot.setData(chapters);

//        index = store.find(valueField, value.getDate());
        //console.debug('onSlotPick store', store, 'count', store.getCount());
        index = store.find(valueField, chapter);
        //console.debug('onSlotPick store.find chapter:', chapter, index);
        if (index == -1) {
            return;
        }

        item = Ext.get(viewItems[index]);

        slot.selectedIndex = index;
        slot.scrollToItem(item);

        slot._value = value;
    },

    getChapterSlot: function() {
        var me = this,
            innerItems = me.getInnerItems(),
            ln = innerItems.length,
            i, slot;

        if (me.chapterSlot) {
            return me.chapterSlot;
        }

        for (i = 0; i < ln; i++) {
            slot = innerItems[i];
            if (slot.isSlot && slot.getName() == "chapter") {
                me.chapterSlot = slot;
                return slot;
            }
        }

        return null;
    },

    // @private
    getChaptersInBook: function(book) {
        //<debug>
        console.debug('getChaptersInBook book', book, booksRecords[book - 1]);
        //</debug>
        return booksRecords[book - 1][2];
    },

    onDoneButtonTap: function() {
        var oldValue = this._value,
            newValue = this.getValue();
        //<debug>
        console.debug('change', newValue);
        //</debug>

        if (newValue.book != oldValue.book || newValue.chapter != oldValue.chapter) {
            this.fireEvent('change', this, newValue);
        }

        this.hide();
    }
});
